package br.com.spacestar.controllers
{
	
	import br.com.spacestar.events.FacebookEvent;
	import br.com.spacestar.services.FacebookService;
	
	import com.adobe.serialization.json.JSON;
	
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	import flash.utils.ByteArray;
	
	import org.swizframework.utils.services.ServiceHelper;
	
	import sk.yoz.events.FacebookOAuthGraphEvent;

	public class FacebookController
	{
		
		[Inject]
		public var facebookService:FacebookService;
		
		[Inject]
		public var serviceHelper:ServiceHelper;
		
		[Dispatcher]
		public var dispatcher:IEventDispatcher;
		
		[Bindable]
		public var connected:Boolean = false;
		
		public function autoConnect():void {
			facebookService.autoConnect(autorized);
		}
		
		public function connect():void {
			facebookService.connect(autorized);
		}
		
		private function autorized(e:FacebookOAuthGraphEvent):void {
			facebookService.call("me/picture", callComplete, true);
			facebookService.call("me",callComplete);
		}
		
		private function callComplete(e:FacebookOAuthGraphEvent):void {
			var event:FacebookEvent;
			if(e.rawData is ByteArray) {
				var loader:Loader = new Loader();
				loader.loadBytes(e.rawData as ByteArray);
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function():void {
					event = new FacebookEvent(FacebookEvent.PICTURE, loader);
					dispatcher.dispatchEvent( event );
				});
			}
			else {
				var obj:Object = JSON.decode(e.rawData as String);
				event = new FacebookEvent(FacebookEvent.DADOS, obj);
				dispatcher.dispatchEvent( event );
			}
		}
	}
}